import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';
import { processUploadedImage, deleteUploadedFile } from '../utils/uploadConfig';

const prisma = new PrismaClient();

/**
 * 推荐菜品请求体接口
 */
interface RecommendedDishBody {
  dishName: string;
  floor?: string;
  price?: number;
}

/**
 * 获取地点的推荐菜品列表
 * GET /api/v1/locations/:id/dishes
 */
export const getLocationDishes = async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    // 检查地点是否存在
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    // 获取推荐菜品列表
    const dishes = await prisma.recommendedDish.findMany({
      where: { locationId },
      include: {
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });

    ResponseHelper.success(res, dishes, '获取成功');

  } catch (error: any) {
    console.error('获取推荐菜品失败:', error);
    ResponseHelper.serverError(res, '获取推荐菜品失败', error);
  }
};

/**
 * 添加推荐菜品
 * POST /api/v1/locations/:id/dishes
 * 需要JWT认证
 */
export const addRecommendedDish = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    let { dishName, floor, price } = req.body as any;

    // 验证必填参数
    if (!dishName) {
      ResponseHelper.validationError(res, [
        { field: 'dishName', message: '菜品名称不能为空' }
      ]);
      return;
    }

    // 检查地点是否存在且已审核通过
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    if (location.status !== 'APPROVED') {
      ResponseHelper.error(res, '该地点暂未通过审核，无法添加推荐菜品', 400);
      return;
    }

    // 处理价格（兼容字符串和数字类型）
    let priceValue: number | null = null;
    if (price !== undefined && price !== null && price !== '') {
      const parsedPrice = typeof price === 'string' ? parseFloat(price) : price;
      if (isNaN(parsedPrice) || parsedPrice < 0) {
        ResponseHelper.validationError(res, [
          { field: 'price', message: '价格必须是大于等于0的数字' }
        ]);
        return;
      }
      priceValue = parsedPrice;
    }

    // 处理上传的图片
    let imageUrl: string | null = null;
    try {
      if (req.file) {
        imageUrl = await processUploadedImage(req.file, 'dishes');
      }
    } catch (imageError) {
      console.error('图片处理失败:', imageError);
      ResponseHelper.error(res, '图片处理失败，请重试', 400);
      return;
    }

    // 创建推荐菜品
    const dish = await prisma.recommendedDish.create({
      data: {
        locationId,
        userId: req.user.id,
        dishName,
        floor: floor || null,
        price: priceValue,
        imageUrl
      },
      include: {
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true
          }
        }
      }
    });

    ResponseHelper.success(res, dish, '添加成功', 201);

  } catch (error: any) {
    console.error('添加推荐菜品失败:', error);
    ResponseHelper.serverError(res, '添加推荐菜品失败', error);
  }
};

/**
 * 更新推荐菜品
 * PUT /api/v1/locations/:locationId/dishes/:dishId
 * 需要JWT认证，仅创建者或管理员可更新
 */
export const updateRecommendedDish = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { locationId, dishId } = req.params;
    const dishIdNum = parseInt(dishId, 10);

    if (isNaN(dishIdNum)) {
      ResponseHelper.validationError(res, [
        { field: 'dishId', message: '无效的菜品ID' }
      ]);
      return;
    }

    // 检查菜品是否存在
    const existingDish = await prisma.recommendedDish.findUnique({
      where: { id: dishIdNum }
    });

    if (!existingDish) {
      ResponseHelper.notFound(res, '推荐菜品不存在');
      return;
    }

    // 权限检查：仅创建者或管理员可更新
    if (existingDish.userId !== req.user.id && req.user.role !== 'ADMIN') {
      ResponseHelper.forbidden(res, '无权修改此推荐菜品');
      return;
    }

    let { dishName, floor, price } = req.body as any;

    // 构建更新数据
    const updateData: any = {};
    if (dishName !== undefined) updateData.dishName = dishName;
    if (floor !== undefined) updateData.floor = floor || null;
    if (price !== undefined && price !== null && price !== '') {
      const parsedPrice = typeof price === 'string' ? parseFloat(price) : price;
      if (isNaN(parsedPrice) || parsedPrice < 0) {
        ResponseHelper.validationError(res, [
          { field: 'price', message: '价格必须是大于等于0的数字' }
        ]);
        return;
      }
      updateData.price = parsedPrice;
    }

    // 处理图片上传
    if (req.file) {
      try {
        // 处理新图片
        const newImageUrl = await processUploadedImage(req.file, 'dishes');
        updateData.imageUrl = newImageUrl;

        // 删除旧图片（如果存在）
        if (existingDish.imageUrl) {
          await deleteUploadedFile(existingDish.imageUrl);
        }
      } catch (imageError) {
        console.error('图片处理失败:', imageError);
        ResponseHelper.error(res, '图片处理失败，请重试', 400);
        return;
      }
    }

    // 更新推荐菜品
    const dish = await prisma.recommendedDish.update({
      where: { id: dishIdNum },
      data: updateData,
      include: {
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true
          }
        }
      }
    });

    ResponseHelper.success(res, dish, '更新成功');

  } catch (error: any) {
    console.error('更新推荐菜品失败:', error);
    ResponseHelper.serverError(res, '更新推荐菜品失败', error);
  }
};

/**
 * 删除推荐菜品
 * DELETE /api/v1/locations/:locationId/dishes/:dishId
 * 需要JWT认证，仅创建者或管理员可删除
 */
export const deleteRecommendedDish = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { locationId, dishId } = req.params;
    const dishIdNum = parseInt(dishId, 10);

    if (isNaN(dishIdNum)) {
      ResponseHelper.validationError(res, [
        { field: 'dishId', message: '无效的菜品ID' }
      ]);
      return;
    }

    // 检查菜品是否存在
    const existingDish = await prisma.recommendedDish.findUnique({
      where: { id: dishIdNum }
    });

    if (!existingDish) {
      ResponseHelper.notFound(res, '推荐菜品不存在');
      return;
    }

    // 权限检查：仅创建者或管理员可删除
    if (existingDish.userId !== req.user.id && req.user.role !== 'ADMIN') {
      ResponseHelper.forbidden(res, '无权删除此推荐菜品');
      return;
    }

    // 删除推荐菜品
    await prisma.recommendedDish.delete({
      where: { id: dishIdNum }
    });

    // 删除关联的图片文件
    if (existingDish.imageUrl) {
      await deleteUploadedFile(existingDish.imageUrl);
    }

    ResponseHelper.success(res, null, '删除成功');

  } catch (error: any) {
    console.error('删除推荐菜品失败:', error);
    ResponseHelper.serverError(res, '删除推荐菜品失败', error);
  }
};
